<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="160px" size="mini">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="运维时间" prop="operationTime">
            <el-date-picker v-model="formItem.operationTime" type="month" placeholder="选择运维时间" value-format="yyyy-MM-dd HH:mm:ss" @change="onMonthChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务月" prop="serviceMonth">
            <el-input v-model="formItem.serviceMonth" placeholder="请输入服务月" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formItem.projectName" placeholder="请输入项目名称" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位名称" prop="clientCode">
            <el-select v-model="formItem.clientCode" placeholder="请选择单位" filterable clearable :disabled="unableSelectUnit" @change="onChangeClient">
              <el-option v-for="item in availableInstitutions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="运维组长" prop="operationUserCode">
            <el-select v-model="formItem.operationUserCode" placeholder="请选择运维组长" disabled>
              <el-option v-for="item in availableOperationUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="驻场工程师" prop="residentEngineerUserName">
            <el-select v-model="formItem.residentEngineerUserCode" placeholder="请选择驻场工程师" filterable clearable :disabled="unableSelectUnit">
              <el-option v-for="item in availableResidentEngineerUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="机动工程师" prop="mobileEngineerUserCode">
            <el-select v-model="formItem.mobileEngineerUserCode" placeholder="请选择机动工程师" filterable clearable>
              <el-option v-for="item in availableMobileEngineerUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="驻场服务总时长" prop="residentServiceTotalTime">
            <el-input v-model="formItem.residentServiceTotalTime" placeholder="请输入驻场服务总时长">
              <template slot="append">分</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="广域网计划外断网时长(分)" prop="unplannedWanOutageDuration">
            <el-input-number v-model="formItem.unplannedWanOutageDuration" :min="0" :max="99999" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="广域网月可用性(%)" prop="wanMonthlyAvailability">
            <el-input-number v-model="formItem.wanMonthlyAvailability" :precision="2" :min="0" :max="99999" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="局域网计划外断网时长(分)" prop="unplannedLanOutageDuration">
            <el-input-number v-model="formItem.unplannedLanOutageDuration" :min="0" :max="99999" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="局域网月可用性(%)" prop="lanMonthlyAvailability">
            <el-input-number v-model="formItem.lanMonthlyAvailability" :precision="2" :min="0" :max="99999" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外联网计划外断网时长(分)" prop="unplannedExtranetOutageDuration">
            <el-input-number v-model="formItem.unplannedExtranetOutageDuration" :min="0" :max="99999" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外联网月可用性(%)" prop="extranetMonthlyAvailability">
            <el-input-number v-model="formItem.extranetMonthlyAvailability" :precision="2" :min="0" :max="99999" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="周报总结" prop="weeklySummary">
            <el-input v-model="formItem.weeklySummary" placeholder="请输入周报总结" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="本月总结" prop="monthSummary">
            <el-input v-model="formItem.monthSummary" placeholder="请输入本月总结" type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户满意度" prop="customerSatisfaction">
            <el-input v-model="formItem.customerSatisfaction" placeholder="请输入用户满意度" type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="重大事件上报" prop="majorIncidentReport">
            <el-input v-model="formItem.majorIncidentReport" placeholder="请输入重大事件上报" type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="下月工作计划" prop="nextMonthWorkPlan">
            <el-input v-model="formItem.nextMonthWorkPlan" placeholder="请输入下月工作计划" type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="合理化建议" prop="reasonableSuggestion">
            <el-input v-model="formItem.reasonableSuggestion" placeholder="请输入合理化建议" type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formItem.remark" placeholder="请输入备注" type="textarea" :autosize="{ minRows: 2, maxRows: 2 }" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <slot />
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :headers="headers"
              :action="importUrl"
              :file-list="formItem.attachment"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-remove="handleRemove"
              :show-file-list="true"
            >
              <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { formatDate, diffMonth, monthBegin, monthEnd } from '@neu/biz-core/utils/utils'
import { create, update, detail } from '@neu/dcom-ui/api/monthWeekly'
import { getInfoByCode as projectInfo } from '@neu/dcom-ui/api/project'
import { list as userList } from '@neu/auth-ui/api/user'
import moment from 'moment'
import { mapState, mapGetters } from 'vuex'
import { page as weekList } from '@neu/dcom-ui/api/operationSupportWeekly'
import { deepClone } from '@neu/biz-core/utils'
import { uploadFileUrl } from '@neu/dcom-ui/api/workDaily'
import { getToken } from '@neu/biz-core/utils/auth'

// 定义一个表单原始项
const formItem = {
  /** 项目名称 */
  projectName: '',
  /** 单位名称 */
  clientName: '',
  /** 单位编码 */
  clientCode: '',
  /** 运维组长名称 */
  operationUserName: '',
  /** 运维组长编码 */
  operationUserCode: '',
  /** 驻场工程师名称 */
  residentEngineerUserName: '',
  /** 驻场工程师编码 */
  residentEngineerUserCode: '',
  /** 机动工程师名称 */
  mobileEngineerUserName: '',
  /** 机动工程师编码 */
  mobileEngineerUserCode: '',
  /** 服务月 */
  serviceMonth: 0,
  /** 广域网计划外断网时长(分) */
  unplannedWanOutageDuration: 0,
  /** 广域网月可用性(%) */
  wanMonthlyAvailability: 100,
  /** 局域网计划外断网时长(分) */
  unplannedLanOutageDuration: 0,
  /** 局域网月可用性(%) */
  lanMonthlyAvailability: 100,
  /** 外联网计划外断网时长(分) */
  unplannedExtranetOutageDuration: 0,
  /** 外联网月可用性(%) */
  extranetMonthlyAvailability: 100,
  /** 驻场服务总时长(分) */
  residentServiceTotalTime: 0,
  /** 运维时间 */
  operationTime: formatDate(new Date()),
  /** 周报总结 */
  weeklySummary: '',
  /** 本月总结 */
  monthSummary: '',
  /** 用户满意度 */
  customerSatisfaction: '',
  /** 重大事件上报 */
  majorIncidentReport: '',
  /** 下月工作计划 */
  nextMonthWorkPlan: '',
  /** 合理化建议*/
  reasonableSuggestion: '',
  /** 服务工作总次数 */
  serviceTotalNumber: '',
  /** 服务工作总耗时 */
  serviceTotalTime: '',
  /** 备注 */
  remark: '',
  /** 附件 */
  attachment: []
}

const formRules = {}

export default {
  name: 'BaseForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      editId: -1,
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: { ...formRules },
      // 运维组长集合
      availableOperationUsers: [],
      // 驻场工程师集合
      availableResidentEngineerUsers: [],
      // 机动工程师集合
      availableMobileEngineerUsers: [],
      // 单位列表
      availableInstitutions: [],
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      importUrl: uploadFileUrl

    }
  },
  computed: {
    ...mapState({
      name: state => state.user.name
    }),
    ...mapGetters([
      'roles'
    ]),
    // 是否可选择厅局
    unableSelectUnit() {
      return this.roles.some(r => r === 'worker')
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    this.availableInstitutions = this.$store.getters['dcom/projectUserInfo'].institutions
    this.formItem.operationUserCode = this.$store.getters['dcom/projectUserInfo'].groupLeader

    // 运维组长集合
    userList({ s_roleCode: 'workerGroupLeader' }).then(res => {
      this.availableOperationUsers = res.data.map(e => { return { name: e.name, username: e.username } })
      this.formItem.operationUserCode = this.$store.getters['dcom/projectUserInfo'].groupLeader
    })

    // 机动工程师集合
    userList({ s_roleCode: 'backup' }).then(res => {
      this.availableMobileEngineerUsers = res.data.map(e => { return { name: e.name, username: e.username } })
    })
  },
  methods: {
    // 初始化表单数据`
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const data = response.data
          if (data.attachment) {
            const fileJoins = data.attachment.split('||')
            data.attachment = fileJoins.map(it => {
              const fsInfo = it.split('@@')
              return {
                fsId: fsInfo[0],
                name: fsInfo[1]
              }
            })
          } else {
            data.attachment = []
          }
          this.formItem = {
            ...data
          }
          this.tmp()
        })
      } else {
        this.formItem = {
          ...formItem
        }
        this.formItem.clientCode = this.$store.getters['dcom/projectUserInfo'].defaultInstituteCode
        this.getWeekWorkList(this.formItem.clientCode)
        this.tmp()
        // 初始化获取项目名称
        this.getProject()
      }
      this.editId = this.id
    },

    tmp() {
      const inst = this.$store.getters['dcom/projectUserInfo'].institutions.find(it => it.code === this.formItem.clientCode)
      if (inst) {
        this.availableResidentEngineerUsers = inst.residents
        let currentResidentUser = inst.residents.find(it => it.name === this.name)
        if (!currentResidentUser) {
          currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
        }
        this.formItem.residentEngineerUserCode = currentResidentUser.username
        this.formItem.residentEngineerUserName = currentResidentUser.name
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.editId !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            // 单位编码
            const client = this.availableInstitutions.find(e => e.code === this.formItem.clientCode)
            this.formItem.clientName = client ? client.name : ''

            // 运维组长集合
            const user1 = this.availableOperationUsers.find(e => e.username === this.formItem.operationUserCode)
            this.formItem.operationUserName = user1 ? user1.name : ''
            // 驻场工程师集合
            const user2 = this.availableResidentEngineerUsers.find(e => e.username === this.formItem.residentEngineerUserCode)
            this.formItem.residentEngineerUserName = user2 ? user2.name : ''
            // 机动工程师集合
            const user3 = this.availableMobileEngineerUsers.find(e => e.username === this.formItem.mobileEngineerUserCode)
            this.formItem.mobileEngineerUserName = user3 ? user3.name : ''

            const deepCloneForm = deepClone(this.formItem)
            // 将附件转为字符串存储
            if (deepCloneForm.attachment.length > 0) {
              deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
            } else {
              deepCloneForm.attachment = ''
            }
            if (updated) {
              resolve(update(this.editId, deepCloneForm))
            } else {
              resolve(create(deepCloneForm))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    /** 获取项目信息 */
    getProject() {
      projectInfo('HN').then(res => {
        const { name, startTime } = res.data
        this.formItem.projectName = name
        this.formItem.serviceMonth = diffMonth(new Date(startTime).getTime(), new Date().getTime())
      })
    },
    onChangeClient(value) {
      this.formItem.residentEngineerUserCode = ''
      this.formItem.residentEngineerUserName = ''
      const inst = this.availableInstitutions.find(it => it.code === value)
      if (inst) {
        this.availableResidentEngineerUsers = inst.residents
        let currentResidentUser = inst.residents.find(it => it.name === this.name)
        if (!currentResidentUser) {
          currentResidentUser = inst.residents.length > 0 ? inst.residents[0] : {}
        }
        this.formItem.residentEngineerUserCode = currentResidentUser.username
        this.formItem.residentEngineerUserName = currentResidentUser.name
      }

      this.getWeekWorkList(value)
    },
    onMonthChange(val) {
      projectInfo('HN').then(res => {
        const { startTime } = res.data
        this.formItem.serviceMonth = diffMonth(new Date(startTime).getTime(), moment(val, 'yyyy-MM-dd HH:mm:ss').unix() * 1000)
      })
      this.getWeekWorkList(this.formItem.clientCode)
    },
    // 获取本月运维服务周报
    getWeekWorkList(companyCode) {
      let dateTime = new Date()
      if (this.formItem.operationTime) {
        dateTime = new Date(this.formItem.operationTime)
      } else {
        dateTime = new Date(this.formItem.createTime)
      }
      this.formItem.weeklySummary = ''
      weekList({
        s_companyCode: companyCode,
        s_afEqReportDate: monthBegin(dateTime.getTime()),
        s_beEqReportDate: monthEnd(dateTime.getTime()),
        sort: 'weekDate,asc',
        size: 2000
      }).then(res => {
        res.data.forEach(item => {
          this.formItem.weeklySummary += moment(item.weekDate).year() + '年' + moment(item.weekDate).week() + '周 工作内容：' + item.summaryDesc + '\n'
        })
      })
    },
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      this.formItem.attachment.splice(this.formItem.attachment.indexOf(file), 1)
    }
  }
}
</script>
